#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFile>
#include <QFileDialog>
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QMenuBar* menubar = new QMenuBar();
    this->setMenuBar(menubar);
    QMenu* menu = new QMenu("文件");
    menubar->addMenu(menu);
    QAction* action = new QAction("打开");
    QAction* action2 = new QAction("保存");
    menu->addAction(action);
    menu->addAction(action2);
    edit = new QPlainTextEdit();
    this->setCentralWidget(edit);
    connect(action, &QAction::triggered, this, &MainWindow::handle);
    connect(action2, &QAction::triggered, this, &MainWindow::handle2);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::handle()
{
    QString str = QFileDialog::getOpenFileName(this);
    QStatusBar* status = new QStatusBar();
    this->setStatusBar(status);
    status->showMessage(str);
    QFile file(str);
    bool rf = file.open(QFile::ReadOnly);
    if(!rf){
        status->showMessage(str + "打开错误");
        return;
    }
    QString text = file.readAll();
    file.close();
    edit->setPlainText(text);
}

void MainWindow::handle2()
{
    QString str = QFileDialog::getSaveFileName();
    QStatusBar* status = this->statusBar();
    status->showMessage(str);
    QFile file(str);
    bool rf = file.open(QFile::WriteOnly);
    if(!rf)
    {
        status->showMessage(str + "打开失败");
        return;
    }
    file.write(((QString)edit->toPlainText()).toUtf8());
    file.close();
}

